/*
 * Copyright 2007-2009 Thomas Krause (thomas@berlin-reloaded.de)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gidoo.cms.editor.structure;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;
import org.gidoo.cms.editor.EditorPage;
import org.gidoo.cms.jcr.EditDataManager;
import org.gidoo.cms.login.GidooCMSSession;

/**
 *
 * @author <a href="mailto:thomas@berlin-reloaded.de">Thomas Krause</a>
 */
public class StructurePanel extends Panel
{

  private Form mainForm;
  private TextField<String> txtNewFolderName;
  private AjaxButton btAdd;
  private AjaxButton btDelete;
  private AjaxButton btUp;
  private AjaxButton btDown;
  private AjaxButton btCut;
  private AjaxButton btPaste;
  private TextField<String> txtRename;
  private AjaxButton btRename;
  
  private EditorPage parentPage;
  
  private String thePagePath;
  
  public StructurePanel(String id, Node page, EditorPage parent)
  {
    super(id);
    
    try
    {

      this.parentPage = parent;   
      if(page == null)
      {
        this.thePagePath = null;
      }
      else
      {
        this.thePagePath = page.getPath();
      }
      mainForm = new Form("mainForm");

      btUp = new AjaxButton("btUp") {

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form)
        {
          folderUp();
          target.addComponent(parentPage.getFeedbackPanel());
          target.addComponent(parentPage.getTreeNav());
          target.addComponent(parentPage.getPanelTabs());
        }
      };
      btUp.setModel( new ResourceModel("up"));
      mainForm.add(btUp);
      
      btDown = new AjaxButton("btDown"){

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form)
        {
          folderDown();
          target.addComponent(parentPage.getFeedbackPanel());
          target.addComponent(parentPage.getTreeNav());
          target.addComponent(parentPage.getPanelTabs());
        }
      };
      btDown.setModel(new ResourceModel("down"));
      mainForm.add(btDown);
      
      txtNewFolderName = new TextField<String>("txtNewFolderName", new Model(""));
      mainForm.add(txtNewFolderName);

      btAdd = new AjaxButton("btAdd")
      {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form)
        {
          addPage();
          target.addComponent(parentPage.getFeedbackPanel());
          target.addComponent(parentPage.getTreeNav());
        }
        
      };
      
      btAdd.setModel(new ResourceModel("add"));
      mainForm.add(btAdd);

      btDelete = new AjaxButton("btDelete") {


        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form)
        {
          deletePage();
          target.addComponent(parentPage.getFeedbackPanel());
          target.addComponent(parentPage.getTreeNav());
        }
      };
      btDelete.setModel(new ResourceModel("delete"));
      mainForm.add(btDelete);

      btCut = new AjaxButton("btCut") {

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form)
        {
          cut();
          target.addComponent(parentPage.getFeedbackPanel());
        }
      };
      btCut.setModel(new ResourceModel("cut"));
      
      btCut.setEnabled(page != null &&
        !"cms:section".equals(page.getPrimaryNodeType().getName()));
      
      mainForm.add(btCut);
      
      btPaste = new AjaxButton("btPaste") {

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form)
        {
          paste();
          
          target.addComponent(parentPage.getFeedbackPanel());
          target.addComponent(parentPage.getTreeNav());
          target.addComponent(parentPage.getPanelTabs());
        }
      };
      btPaste.setModel(new ResourceModel("paste"));
      
      btPaste.setEnabled(
        page != null &&
        parentPage.getLastCutPath() != null 
        && !parentPage.getLastCutPath().equals(page.getPath()));
      
      mainForm.add(btPaste);
      
      txtRename = new TextField<String>("txtRename", new Model(""));
      txtRename.setEnabled(page != null && 
        !"cms:section".equals(page.getPrimaryNodeType().getName()));
      mainForm.add(txtRename);
      
      btRename = new AjaxButton("btRename") {

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form)
        {
          rename();
          target.addComponent(parentPage.getFeedbackPanel());
          target.addComponent(parentPage.getTreeNav());
          target.addComponent(parentPage.getPanelTabs());
          
        }
      };      
      btRename.setModel(new ResourceModel("rename"));
      btRename.setEnabled(page != null &&
        !"cms:section".equals(page.getPrimaryNodeType().getName()));
      mainForm.add(btRename);
      
      add(mainForm);

      if(page == null)
      {
        mainForm.setVisible(false);
      }
      else if("cms:section".equals(page.getPrimaryNodeType().getName()))
      {
        btDelete.setVisible(false);
      }
    }
    catch(RepositoryException ex)
    {
      Logger.getLogger(StructurePanel.class.getName()).log(Level.SEVERE, null, ex);
      error("jcrerror");
    }

  }

  private void rename()
  {
    
    Session session = ((GidooCMSSession) getSession()).getJcrSession();
    
    try
    {
      Node page = session.getRootNode().getNode(thePagePath.substring(1));
      String newName = txtRename.getModelObject();
     
      Node result =
        EditDataManager.renamePage(page, newName, (GidooCMSSession) getSession());
      if(result != null)
      {
          thePagePath = result.getPath();
      }   
      
      parentPage.updateDataAndView(page);
    }
    catch (RepositoryException ex)
    {
      Logger.getLogger(StructurePanel.class.getName()).log(Level.SEVERE, null, ex);
      error(getString("jcrerror"));
      parentPage.updateDataAndView();
    }
  }
  
  private void cut()
  {
    try
    {
      Session session = ((GidooCMSSession) getSession()).getJcrSession();
      Node page = session.getRootNode().getNode(thePagePath.substring(1));

      if("cms:section".equals(page.getPrimaryNodeType().getName()))
      {
        error(getString("sectionnotallowed"));
        return;
      }
      parentPage.setLastCutPath(thePagePath);
      info(getString("wascutted"));
    }
    catch(RepositoryException ex)
    {
      Logger.getLogger(StructurePanel.class.getName()).log(Level.SEVERE, null, ex);
      error(getString("jcrerror"));
    }
  }
  
  private void paste()
  {
    if(parentPage.getLastCutPath() != null)
    {
      try
      {
        Session session = ((GidooCMSSession) getSession()).getJcrSession();
        Node pageToMove = 
          session.getRootNode().getNode(parentPage.getLastCutPath().substring(1));
        Node currentPage = session.getRootNode().getNode(thePagePath.substring(1));
        
        parentPage.setLastCutPath(null);
       
        Node result =
          EditDataManager.movePage(pageToMove, currentPage, (GidooCMSSession) getSession());
        
        if(result != null)
        {
          info(getString("moved"));
        }
        
        parentPage.updateDataAndView(pageToMove);
        
      }
      catch (RepositoryException ex)
      {
        Logger.getLogger(StructurePanel.class.getName()).log(Level.SEVERE, null, ex);
        error(getString("jcrerror"));
      }
      
    }
  }
  
  private void addPage()
  {
    if(thePagePath == null)
    {
      warn(getString("null"));
      return;
    }

    String name = txtNewFolderName.getModelObject();
    
    GidooCMSSession s = (GidooCMSSession) getSession();
    try
    {
      Node parent = s.getJcrRootNode().getNode(thePagePath.substring(1));

      EditDataManager.addNewPage(name, parent, s);
    }
    catch(RepositoryException ex)
    {
      Logger.getLogger(StructurePanel.class.getName()).log(Level.SEVERE, null, ex);
      error(getString("jcrerror"));
    }
    parentPage.updateDataAndView();
    
  }

  private void deletePage()
  {
    Node toSelect = parentPage.getCurrentSelectedPage();
      
    try
    {
      if(thePagePath == null)
      {
        warn(getString("null"));
        return;
      }
      
      Node root = ((GidooCMSSession) getSession()).getJcrRootNode();
      Node page = root.getNode(thePagePath.substring(1));
      Node parent = page.getParent();
      
      if(EditDataManager.deletePage(page, (GidooCMSSession) getSession()))
      {
        toSelect = parent;
      }
      
    }
    catch(RepositoryException ex)
    {
      Logger.getLogger(StructurePanel.class.getName()).log(Level.SEVERE, null, ex);
      error(getString("jcrerror"));
    }
    
    parentPage.updateDataAndView(toSelect);
    
  }
  
  private void folderDown()
  {
    if(thePagePath == null)
      return;
    
    try
    {
      GidooCMSSession session = ((GidooCMSSession) getSession());
      Node page = session.getJcrRootNode().getNode(thePagePath.substring(1));
      
      EditDataManager.pageDown(page, session);
    }
    catch (RepositoryException ex)
    {
      Logger.getLogger(StructurePanel.class.getName()).log(Level.SEVERE, null, ex);
      error(getString("jcrerror"));
    }
    
    parentPage.updateDataAndView();
  }
  
  private void folderUp()
  {
    if(thePagePath == null)
      return;
    GidooCMSSession s = (GidooCMSSession) getSession();
    Node page;
    try
    {
      page = s.getJcrRootNode().getNode(thePagePath.substring(1));
      EditDataManager.pageUp(page, s);
    }
    catch(RepositoryException ex)
    {
      Logger.getLogger(StructurePanel.class.getName()).log(Level.SEVERE, null, ex);
    }
    
    parentPage.updateDataAndView();
  }

}
